<script type="text/html" template lay-done="layui.data.attenceUpdatedone(d);">
    <div class='attence-updateHtml-content'>
        <div class="layui-card card-content">
            <div class="layui-card-body main-box">
                <div class="layui-innerbox" style="background-color: #fff;">
                    <div class="layui-row">
                        <div class="layui-col-md6">
                            <form class="layui-form attence-updateHtml-form" action="" lay-filter="attence-updateHtml-form-group">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">任务名称：</label>
                                    <div class="layui-input-inline" style="margin-left:23px;">
                                        <input type="text" class="layui-hide" name="id" value='{{d.params.id ? d.params.id : ""}}'>
                                        <input type="text" class="layui-hide" name="taskid" value='{{d.params.id ? d.params.id : ""}}'>
                                        <input type="text" value='{{d.params.taskname ? d.params.taskname : ""}}' name="taskname" lay-verify="taskname" autocomplete="off" placeholder="请输入标题" class="layui-input">
                                    </div>
                                    <span class="redstar">*</span>
                                </div>
                                <div class="layui-form-item" style="margin-top: 26px;">
                                    <div class="layui-form-item layui-form-text">
                                        <label class="layui-form-label">备注信息：</label>
                                        <div class="layui-input-block">
                                            <textarea name="memo" placeholder="请输入内容" class="layui-textarea" style="min-height: 112px;">
                                                    {{d.params.memo ? d.params.memo : ""}}
                                            </textarea>
                                        </div>
                                    </div>
                                    <div class="special-content">
                                        <div class="special-key">
                                            <button type="button" class="layui-btn layui-btn-xs" id="attence-upload-filie"><i class="layui-icon"></i>附件</button>
                                        </div>
                                        <div class="special-value">
                                            <div class="check-value-box attence-update-files"></div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="layui-col-md6">
                            <form class="layui-form attence-frequency-form" action="" lay-filter="attence-frequency-form">
                                <div class="layui-form-item">
                                    <div style="display:none;">
                                        <label class="layui-form-label" style="text-align:left;">时间设置：</label>
                                        <div class="layui-input-block">
                                            <div class="leftType">
                                                <div class="topLeftType">
                                                    <input type="radio" name="timeType" value="frequency" title="固定频率" lay-filter="timeType" {{ d.params.settype && d.params.settype === '0' ? "checked" : null}}>
                                                </div>
                                                <div class="bottomLeftType">
                                                    <input type="radio" name="timeType" value="time" title="固定时间" lay-filter="timeType" {{ d.params.settype && d.params.settype === '1' ? "checked" : null}}>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="frequencyType" style="display:none;">
                                        <div class="frequencyTypeDiv">
                                            <input type="radio" name="frequencyType" lay-filter="frequencyTimeType" value="year" title="每年" {{ d.params.settype && d.params.settype === '1' ? "disabled" : null}} {{ d.params.hz && d.params.hz === 'year' ? "checked" : null}}>
                                        </div>
                                        <div class="frequencyTypeDiv">
                                            <input type="radio" name="frequencyType" lay-filter="frequencyTimeType" value="quarter" title="每季度" {{ d.params.settype && d.params.settype === '1' ? "disabled" : null}} {{ d.params.hz && d.params.hz === 'quarter' ? "checked" : null}}>
                                        </div>
                                        <div class="frequencyTypeDiv">
                                            <input type="radio" name="frequencyType" lay-filter="frequencyTimeType" value="month" title="每月" {{ d.params.settype && d.params.settype === '1' ? "disabled" : null}} {{ d.params.hz && d.params.hz === 'month' ? "checked" : null}}>
                                        </div>
                                        <div class="frequencyTypeDiv">
                                            <input type="radio" name="frequencyType" lay-filter="frequencyTimeType" value="week" title="每周" {{ d.params.settype && d.params.settype === '1' ? "disabled" : null}} {{ d.params.hz && d.params.hz === 'week' ? "checked" : null}}>
                                        </div>
                                        <div class="frequencyTypeDiv">
                                            <input type="radio" name="frequencyType" lay-filter="frequencyTimeType" value="day" title="每日" {{ d.params.settype && d.params.settype === '1' ? "disabled" : null}} {{ d.params.hz && d.params.hz === 'day' ? "checked" : null}}>
                                        </div>
                                    </div>
                                    <div class="layui-input-block fill-time-block" style="margin-top: 5px;">
                                        <div class="layui-form-item"  style="padding: 10px 10px 0px 10px;">
                                            <div class="dateType" lay-filter="frequencyDateType"></div>
                                            <div class="listType">
                                                <div class="header">
                                                    最近5次填报时间
                                                    <button type="button" style="float: right;" class="layui-btn layui-btn-sm T-event" data-target="viewlast">查看</button>
                                                </div>
                                                <div class="body"></div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div> 
                </div>
                <div class="layui-collapse" style="margin-bottom:40px;">
                    <div class="layui-colla-item">
                        <h2 class="layui-colla-title c-iframeTitle" style="height:24px;line-height:24px;overflow: visible;"> <span>单位: {{layui.data('userdata').data.dept_name}}</span></h2>
                        <div class="layui-colla-content table-area" style="background-color: #fff;color: black;padding:10px 10px 0px 10px;">
                            <div class="search-area layui-form attence-search-form" action="" lay-filter="attence-search-form" style="height: 40px;margin-bottom: 10px;">
                                <div class="date-group" style="float: right;">
                                    考勤时间：
                                    <div class="layui-input-inline" style="width: 150px;">
                                        <input type="text" name="starttime" class="layui-input item-time item-time-start" 
                                        value='{{d.params.timeScope ? d.params.timeScope.starttime : ""}}' lay-verify="date" autocomplete="off" readonly data-timetype="start" placeholder="选择时间">
                                    </div>
                                    <div style="display: inline-block;">-</div>
                                    <div class="layui-input-inline" style="width: 150px;">
                                        <input type="text" name="endtime" class="layui-input item-time item-time-end"  
                                        value='{{d.params.timeScope ? d.params.timeScope.endtime : ""}}' lay-verify="date" autocomplete="off" readonly data-timetype="end" placeholder="选择时间">
                                    </div>
                                    <!-- <button type="button" class="layui-btn layui-btn-sm" data-target="choice">选择人员</button> -->
                                </div>
                            </div>
                            <div class="attence-table-container" id="attence-table-page"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="buttons-area">
                <button type="button" class="T-event layui-btn" data-target="add">{{d.params.id ? '修改' : '创建'}}任务</button>
            </div>
        </div>
    </div>
</script>
<style>
.attence-updateHtml-content .c-iframeTitle {
    height:24px;
    line-height:24px;
    -moz-user-select:none;
    -ms-user-select: none;
    -webkit-user-select: none;
    user-select: none;
    overflow: visible;
}
.attence-updateHtml-content {
    height: 100%;
    overflow: hidden;
}
.attence-updateHtml-content .card-content {
	height: 100%;
    overflow: auto;
    background-color: #fff;
}
.attence-updateHtml-content .layui-form-item{
    margin: 0;
}
.layui-innerbox{
    border: 1px solid #D2D2D2;
    border-radius: 4px;
    padding-top: 17px;
}
.attence-updateHtml-content .redstar{
    display: block;
    color: red;
    line-height: 45px;
    height: 0px;
}
.attence-updateHtml-content .layui-form-item .layui-input-inline {
    width: 67%;
    margin-right: 5px;
}
.attence-updateHtml-content .layui-input-block{
    width: 67%;
}
.attence-updateHtml-content .fill-time-block {
    border: 1px solid rgb(167,198,238);
    border-radius: 6px;
    width: 100% !important;
    height: auto;
    margin: 0;
    /* -ms-behavior: url(../../dist/style/res/PIE.htc);
    behavior: url(../../dist/style/res/PIE.htc); */
}
.attence-updateHtml-content .layui-form-switch {
    background: #D2D2D2;
    width: 60%;
}
.attence-updateHtml-content .layui-form-switch em {
    margin-left: 28px;
    color: #fff!important;
}
.attence-updateHtml-content .layui-form-onswitch em {
    margin-left: 9px !important;
}
.attence-updateHtml-content .layui-form-switch i {
    background-color: #fff;
}
.attence-updateHtml-content .layui-form-onswitch i {
    margin-left: -22px;
}
.attence-updateHtml-content .layui-btn-xs {
    height: 38px;
    background: #2669B1;
    margin-top: -8px;
    border-radius: 5px;
    width: 90px;
    margin-left: 5px;
   /*  -ms-behavior: url(../../dist/style/res/PIE.htc);
    behavior: url(../../dist/style/res/PIE.htc); */
}
.attence-updateHtml-content .special-value {
    overflow: hidden;
    border: 1px solid #ccc;
    height: 38px;
    width: 67%;
    border-radius: 6px;
    border: 1px solid rgb(197,197,197);
    /* -ms-behavior: url(../../dist/style/res/PIE.htc);
    behavior: url(../../dist/style/res/PIE.htc); */
}
.attence-updateHtml-content .layui-input, .layui-textarea{
    border-radius: 6px;
    border: 1px solid rgb(197,197,197);
    /* -ms-behavior: url(../../dist/style/res/PIE.htc);
    behavior: url(../../dist/style/res/PIE.htc); */
}
.attence-updateHtml-content .layui-form-onswitch{
    border-color: #2669B1;
    background-color: #2669B1;
}
.attence-updateHtml-content .special-content {
    width: 100%;
    margin-top: 26px;
}
.attence-updateHtml-content .special-key {
    overflow: hidden;
    width: 96px;
    float: left;
    padding: 9px 3px;
    padding-right: 10px;
    text-align: right;
}
.attence-updateHtml-content .iframeContent {
    width: 100%;
    height: 532px;
    overflow: hidden;
}

.attence-updateHtml-content .iframeContent .attence-updateHtml-form {
    width: 99%;
    height: 100%;
    overflow: auto;
}
.attence-updateHtml-form{
    background-color: #FFFFFF;
    padding: 11px;
}
.attence-updateHtml-content .buttons-area {
    position: absolute;
	bottom: 0px;
	left: 0px;
	width: 100%;
	height: 40px;
	text-align: center;
	margin-top: 10px;
    height: 40px;
    background-color: #FFFFFF;
}
.buttons-area button{
    background-color: #2669B1;
}
.attence-updateHtml-content .check-value-box {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    padding: 2px 2px;
}
.attence-updateHtml-content .unit-content {
    display: inline-block;
    padding: 2px 5px;
    padding-right: 15px;
    background-color: #ccc;
    position: relative;
    height: 20px;
    line-height: 20px;
}

.attence-updateHtml-content .unit-content:hover i{
    visibility: visible;
    color: red;
    font-weight: 600;
}

.attence-updateHtml-content .unit-content i {
    position: absolute;
    right: 0px;
    top: -2px;
    font-size: 14px;
    cursor: pointer;
    visibility: hidden;
}
.attence-updateHtml-content .layui-form-radio {
    margin: 6px 0px 0 0px;
}
.attence-updateHtml-content .layui-form-radio>i:hover, .layui-form-radioed>i {
    color: #276AB1;
}
.attence-updateHtml-content .layui-input-block .leftType {
    width: 100%;
    height: 40px;
    display: flex;
}
.attence-updateHtml-content .frequencyType {
    width: 100%;
    margin: 0 auto;
    height: 40px;
    display: flex;
    border-bottom: 1px rgb(210,210,210) solid;
}
.attence-updateHtml-content .frequencyTypeDiv {
    float: left;
    width: 20%;
    height: 40px;
}
.attence-frequency-form{
    width: 90%;
    margin: 10px auto;
    margin-top: 0px;
}
.attence-frequency-form .dateType {
    width: 65%;
    height: 100%;
    min-height: 187px;
    float: left;
    border-right: 1px solid #ccc;
}
.attence-frequency-form .date-item {
    width: 100%;
    height: 32px;
    clear: both;
    display: flex;
}
.attence-frequency-form .dateType .layui-btn-sm{
    height: 30px;
    line-height: 23px;
    padding: 0px 6px 0px 8px;
    font-size: 12px;
    border: 1px #009688 solid;
    background-color: transparent;
    border-radius: 6px;
    color: #009688;
    margin-right: 5px;
    /* -ms-behavior: url(../../dist/style/res/PIE.htc);
    behavior: url(../../dist/style/res/PIE.htc); */
}
.attence-frequency-form .listType .layui-btn-sm{
    height: 30px;
    line-height: 23px;
    padding: 0px 6px 0px 8px;
    font-size: 12px;
    border: 1px #009688 solid;
    background-color: transparent;
    border-radius: 6px;
    color: #009688;
    /* -ms-behavior: url(../../dist/style/res/PIE.htc);
    behavior: url(../../dist/style/res/PIE.htc); */
}
.attence-frequency-form .date-item input {
    line-height: 32px;
}
.attence-frequency-form .dateType .layui-form-mid {
    padding: 7px 0px !important;
}
.attence-frequency-form .date-item .layui-input {
    height: 30px;
}
.attence-frequency-form .listType {
    width: 34%;
    float: left;
    height: 100%;
}
.attence-frequency-form .listType .header {
    height: 30px;
    text-align: center;
    line-height: 30px;
    font-size: 14px;
}
.attence-frequency-form .listType .body {
    height: 157px;
    overflow-y: auto;
    text-align: center;
}
/* 滚动条样式 */
::-webkit-scrollbar{
	width: 4px;
	height: 4px;
}
::-webkit-scrollbar-thumb{
	border-radius: 5px;
    -webkit-box-shaow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: rgba(0,0,0,0.2);
}
::-webkit-scrollbar-track{
	border-radius: 0;
    background: rgba(0,0,0,0.1);
}

.layui-layer{
	border-radius: 8px;
}
.layui-form-label{
	padding: 8px 3px;
}
.layui-layer-setwin{
    top: 10px;
    right: 11px;
}
.layui-layer-setwin .layui-layer-close1{
    background-position: 0 0;
}
.layui-layer-setwin a{
    width: 18px;
    height: 18px;
    margin: 0;
    background: url('/src/style/res/formFill/layer-close.png') no-repeat center center;
    background-position: 0px 0px;
}
.main-box{
    padding: 0 10px;
}
/* .attence-updateHtml-content .layui-card{
    background: linear-gradient(137deg, #1D5BAE, #51AFBC);
} */
.attence-updateHtml-content .layui-form-item .layui-inline .layui-review-box span{
    display: inline-block;
    height: 40px;
    line-height: 40px;
    color: #666;
    cursor: pointer;
    vertical-align: top;
}
.layui-review-box{
    margin-top: 10px;
}
.layui-review-box span:hover{
    text-decoration: underline;
}
.to-verify{
    margin-left: 78px;
}
.review-value-box, .audit-value-box{
    height: 38px;
    line-height: 20px;
}
.attence-table-container {
    width: 100%;
    height: 450px;
    overflow: auto;
}
#addItem{
    display: none;
}
</style>
<script type="text/html" id="attenceTimeItemTpl">
    {{# 
        var isFirst=d.isFirst;
    }}
    <div class="date-item">
        <div class="layui-input-inline" style="width: 122px;">
            <input type="text" name="starttime" value="{{d.data.starttime || ''}}" class="layui-input item-time item-time-start" autocomplete="off" readonly data-timetype="start" placeholder="选择时间">
        </div>
        <div class="layui-input-inline" style="width: 5px;">-</div>
        <div class="layui-input-inline" style="width: 122px;">
            <input type="text" name="endtime" value="{{d.data.endtime || ''}}" class="layui-input item-time item-time-end" autocomplete="off" readonly data-timetype="end" placeholder="选择时间">
        </div>
        {{# if(!!isFirst) { }}
        <button type="button" id="addItem" class="layui-btn layui-btn-sm T-bEvent" data-target="addItem">
            <i class="layui-icon">&#xe654;</i>
        </button>
        {{# } else {  }}
        <button type="button" class="layui-btn layui-btn-sm T-bEvent" data-target="delItem">
            <i class="layui-icon">&#x1006;</i>
        </button>
        {{# } }}
    </div>
</script>
<script type="text/html" id="attenceselectunitTpl">
    {{#
        layui.each(d, function(index,item) {
    }}
        <div class="unit-content">
            {{item.writeusername}}
            <i class="layui-icon layui-icon-close T-event unit" data-target="delUnit" data-deptid="{{item.dataid}}"></i>
        </div>
    {{#
        })
    }}
</script>
<script type="text/html" id="attenceselectgroupTpl">
    {{#
        layui.each(d, function(index,item) {
    }}
        <div class="unit-content">
            {{item.writeusername}}
            <i class="layui-icon layui-icon-close T-event group" data-target="delUnit" data-deptid="{{item.dept_id}}"></i>
        </div>
    {{#
        })
    }}
</script>
<script type="text/html" id="attenceShowLastTpl">
    {{#
        layui.each(d, function(index,item) {
    }}
        <div style="background-color:#ccc;border-radius: 6px;margin-top: 5px;">
            <p>开始：{{item.starttime}}</p>
            <p>结束：{{item.endtime}}</p>
        </div>
    {{#
        })
    }}
</script>
<script type="text/html" id="attenceuploadFilesTpl">
    {{#
        layui.each(d, function(index,item) {
    }}
        <div class="unit-content">
            <a class="T-event" data-target="download" href="javascript: void(0);" data-url="{{item.url}}">{{item.filename}}</a>
            <i class="layui-icon layui-icon-close T-event" data-target="delFile" data-deptid="{{item.servername}}"></i>
        </div>
    {{#
        })
    }}
</script>
<script>
layui.data.attenceUpdatedone = function (d) {  
    layui.use(['admin', 'form', 'laydate', 'upload', 'tools'], function(){
        var $ = layui.$,
        admin = layui.admin,
        view = layui.view,
        element = layui.element,
        layer = layui.layer,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        upload = layui.upload,
        setter = layui.setter,
        tools = layui.tools,
        form = layui.form,
        filenames = [],
        tableUsers = [],
        tableDates = [],
        timeInputType = 'month'; // year, quarter, month, week ,day
        
        form.render(null, 'attence-updateHtml-form-group');
        form.render(null, 'attence-frequency-form');
        form.render(null, 'attence-search-form');
        element.render();

        //搜索区域绑定时间
        bindSearchTime();

        var tempFileName = '';
        upload.render({
            elem: '#attence-upload-filie',
            accept: 'file',
            url: 'myapi/DC/api/rest/web/custom/uploadfile?access_token='+layui.data('layuiAdmin').access_token,
            choose: function(obj) {
                obj.preview(function(index, file, result){
                    tempFileName = file.name;
                });
            },
            done: function(res, index, upload){ //上传后的回调
                if(res.retcode == 0) {
                    // filenames.push({filename: tempFileName, servername: res.servername}); 
                    filenames.push({filename: res.filename, servername: res.servername, url: res.url});
                    var getTpl = attenceuploadFilesTpl.innerHTML,
                        $tplC =$('.attence-update-files');
                    laytpl(getTpl).render(filenames, function(html){
                        $tplC.html(html);
                    });
                }else {
                    layer.msg('提示: '+ res.retmsg,{time: 1000});
                }
            },
            error: function(index, upload){
                layer.msg('上传文件过大，请重新选择文件上传', {time: 1000});
            }
        });
        if(d.params.id) { //修改 
            var timeDate = d.params.timeDate && d.params.timeDate.length && d.params.timeDate.length > 0 ? d.params.timeDate : [];
            if(timeDate.length > 0) {
                $.each(timeDate, function(index, item) {
                    item.starttime = moment(item.starttime).format('YYYY-MM-DD HH:mm');
                    item.endtime = moment(item.endtime).format('YYYY-MM-DD HH:mm');
                    insertDateTplByType(index === 0, item);
                })
            }else {
                insertDateTplByType(true);
            }
            var exitFileNames = d.params.fileNames;
            if(exitFileNames.length > 0) {
                filenames = exitFileNames;
                var Tplhtml = attenceuploadFilesTpl.innerHTML;
                var $tplF =$('.attence-update-files');
                laytpl(Tplhtml).render(exitFileNames, function(html){
                    $tplF.html(html);
                });
            }

            var initData = {};
            var dates = d.params.users && d.params.users.length > 0 ? d.params.users[0].users_time[0].users_time_day : [];
            initData.dates = dates;
            tableUsers = d.params.users || [];
            tableDates = dates;
            initData.users = tableUsers;
            renderTable(initData);
        }else { //新增
            addInit();
            insertDateTplByType(true);
        }
        
        //表单中时间频率类型改变事件
        form.on('radio(timeType)', function(data){
            var $form = $('.attence-updateHtml-content .attence-frequency-form');
            var timeTypeValue = data.value;
            if(timeTypeValue === 'frequency') {
                $form.find('.leftType input[name="timeType"][value="frequency"]').attr('checked', true);
                $form.find('.leftType input[name="timeType"][value="time"]').attr('checked', false);
                $form.find('.frequencyType input:radio').each(function(i, el) {
                    $(el).attr('disabled', false);
                    if(i===2) {
                        $(el).attr('checked', true);
                        $(el).click();
                    }
                });
                form.render('radio', 'attence-frequency-form');
                timeInputType = 'month';
            }else if(timeTypeValue === 'time') {
                $form.find('.leftType input[name="timeType"][value="time"]').attr('checked', true);
                $form.find('.leftType input[name="timeType"][value="frequency"]').attr('checked', false);
                $form.find('.frequencyType input:radio').each(function(i, el) {
                    $(el).attr('disabled', true);
                })
                $form.find('input[name="frequencyType"]').removeAttr('checked');
                form.render('radio', 'attence-frequency-form');
                timeInputType = 'year';
            }
            insertDateTplByType(true);
        });

        //表单中时间频率类型改变事件
        form.on('radio(frequencyTimeType)', function(data){
            var $form = $('.attence-updateHtml-content .attence-frequency-form');
            var frequencyTimeTypeValue = data.value;
            timeInputType = frequencyTimeTypeValue;
            insertDateTplByType(true);
        });

        //频率类型为频率时，根据时间来插入不同的时间选择组件
        function insertDateTplByType(isFirst,values) {
            var getTpl = attenceTimeItemTpl.innerHTML;
            var $tplC =$('.attence-frequency-form .dateType');
            laytpl(getTpl).render({isFirst: isFirst, data: !!values ? values : {} }, function(html){
                var $ItemHtml = $(html);
                //给第一个时间行绑定时间组件
                bindTypeForItem($ItemHtml);
                !!isFirst ? $tplC.html($ItemHtml) : $tplC.append($ItemHtml);
                form.render(null, 'attence-frequency-form');
            });
        }

        //给时间行绑定相应的时间操作
        function bindTypeForItem($ItemContariner) {
            $ItemContariner.each(function(index, el) {
                var commonMin = { year: 1900, month: 0, date: 1},
                    commonMax = { year: 2099, month: 11, date: 31};
                switch(timeInputType) {
                    case 'year':
                    var startDate = laydate.render({
                        elem: $ItemContariner.find('.item-time-start').get(0),
                        min: tools.minDate('date'),
                        type: 'datetime',
                        format: 'yyyy-MM-dd HH:mm',
                        done: function (value, date) {
                            if(!!value) {
                                endDate.config.min = {
                                    year:date.year,
                                    month:date.month-1, 
                                    date: date.date,
                                };
                                endDate.config.max ={
                                    year: date.year+1,
                                    month:date.month-1, 
                                    date: date.date,
                                };
                            }else {
                                endDate.config.min = commonMin;
                                endDate.config.max = commonMax;
                            }
                        }
                    })
                    var endDate = laydate.render({
                        elem: $ItemContariner.find('.item-time-end').get(0),
                        type: 'datetime',
                        format: 'yyyy-MM-dd HH:mm',
                        done: function (value, date) {
                            if(!!value) {
                                startDate.config.min = {
                                    year: date.year-1,
                                    month: date.month - 1,
                                    date: date.date,
                                } 
                                startDate.config.max = {
                                    year: date.year,
                                    month: date.month - 1,
                                    date: date.date,
                                } 
                            }else {
                                startDate.config.min = commonMin;
                                startDate.config.max = commonMax; 
                            }
                        }
                    });
                    break;
                    case 'quarter':
                    var startDate = laydate.render({
                        elem: $ItemContariner.find('.item-time-start').get(0),
                        min: tools.minDate('date'),
                        type: 'datetime',
                        format: 'yyyy-MM-dd HH:mm',
                        done: function (value, date) {
                            if(!!value) {
                                endDate.config.min = {
                                    year:date.year,
                                    month:date.month-1, 
                                    date: date.date,
                                };
                                var newDate = moment(value).add(3, 'M');
                                endDate.config.max ={
                                    year: newDate.year(),
                                    month: newDate.month(),
                                    date: newDate.date(),
                                };
                            }else {
                                endDate.config.min = commonMin;
                                endDate.config.max = commonMax;
                            }
                        }
                    })
                    var endDate = laydate.render({
                        elem: $ItemContariner.find('.item-time-end').get(0),
                        type: 'datetime',
                        format: 'yyyy-MM-dd HH:mm',
                        done: function (value, date) {
                            if(!!value) {
                                var newDate = moment(value).subtract(3, 'M');
                                startDate.config.min = {
                                    year: newDate.year(),
                                    month: newDate.month(),
                                    date: newDate.date(),
                                } 
                                startDate.config.max = {
                                    year: date.year,
                                    month: date.month - 1,
                                    date: date.date,
                                } 
                            }else {
                                startDate.config.min = commonMin;
                                startDate.config.max = commonMax; 
                            }
                        }
                    });
                    break;
                    case 'month':
                    var startDate = laydate.render({
                        elem: $ItemContariner.find('.item-time-start').get(0),
                        min: tools.minDate('date'),
                        type: 'datetime',
                        format: 'yyyy-MM-dd HH:mm',
                        done: function (value, date) {
                            if(!!value) {
                                endDate.config.min = {
                                    year:date.year,
                                    month:date.month-1, 
                                    date: date.date,
                                };
                                var newDate = moment(value).add(1, 'M');
                                endDate.config.max ={
                                    year: newDate.year(),
                                    month: newDate.month(),
                                    date: newDate.date(),
                                };
                            }else {
                                endDate.config.min = commonMin;
                                endDate.config.max = commonMax;
                            }
                        }
                    })
                    var endDate = laydate.render({
                        elem: $ItemContariner.find('.item-time-end').get(0),
                        type: 'datetime',
                        format: 'yyyy-MM-dd HH:mm',
                        done: function (value, date) {
                            if(!!value) {
                                var newDate = moment(value).subtract(1, 'M');
                                startDate.config.min = {
                                    year: newDate.year(),
                                    month: newDate.month(),
                                    date: newDate.date(),
                                } 
                                startDate.config.max = {
                                    year: date.year,
                                    month: date.month - 1,
                                    date: date.date,
                                } 
                            }else {
                                startDate.config.min = commonMin;
                                startDate.config.max = commonMax; 
                            }
                        }
                    });
                    break;
                    case 'week':
                        var startDate = laydate.render({
                            elem: $ItemContariner.find('.item-time-start').get(0),
                            min: tools.minDate('date'),
                            type: 'datetime',
                            format: 'yyyy-MM-dd HH:mm',
                            done: function (value, date) {
                                if(!!value) {
                                    endDate.config.min = {
                                        year:date.year,
                                        month:date.month-1, 
                                        date: date.date,
                                    };
                                    var newDate = moment(value).add(1, 'w');
                                    endDate.config.max ={
                                        year: newDate.year(),
                                        month: newDate.month(),
                                        date: newDate.date(),
                                    };
                                }else {
                                    endDate.config.min = commonMin;
                                    endDate.config.max = commonMax;
                                }
                            }
                        })
                        var endDate = laydate.render({
                            elem: $ItemContariner.find('.item-time-end').get(0),
                            type: 'datetime',
                            format: 'yyyy-MM-dd HH:mm',
                            done: function (value, date) {
                                if(!!value) {
                                    var newDate = moment(value).subtract(1, 'w');
                                    startDate.config.min = {
                                        year: newDate.year(),
                                        month: newDate.month(),
                                        date: newDate.date(),
                                    } 
                                    startDate.config.max = {
                                        year: date.year,
                                        month: date.month - 1,
                                        date: date.date,
                                    } 
                                }else {
                                    startDate.config.min = commonMin;
                                    startDate.config.max = commonMax; 
                                }
                            }
                        });
                    break;
                    case 'day':
                    var startDate = laydate.render({
                        elem: $ItemContariner.find('.item-time-start').get(0),
                        min: tools.minDate('datetime'),
                        type: 'datetime',
                        format: 'yyyy-MM-dd HH:mm',
                        done: function (value, date) {
                            if(!!value) {
                                endDate.config.min = {
                                    year:date.year,
                                    month:date.month-1, 
                                    date: date.date,
                                    hours: date.hours,
                                    minutes: 0,
                                    seconds: 0
                                };
                                var newDate = moment(value).add(1, 'd');
                                endDate.config.max ={
                                    year: newDate.year(),
                                    month: newDate.month(),
                                    date: newDate.date(),
                                    hours: newDate.hours(),
                                    minutes: 0,
                                    seconds: 0
                                };
                            }else {
                                endDate.config.min = commonMin;
                                endDate.config.max = commonMax;
                            }
                        }
                    })
                    var endDate = laydate.render({
                        elem: $ItemContariner.find('.item-time-end').get(0),
                        type: 'datetime',
                        format: 'yyyy-MM-dd HH:mm',
                        done: function (value, date) {
                            if(!!value) {
                                var newDate = moment(value).subtract(1, 'd');
                                startDate.config.min = {
                                    year: newDate.year(),
                                    month: newDate.month(),
                                    date: newDate.date(),
                                    hours: newDate.hours(),
                                    minutes: 0,
                                    seconds: 0
                                } 
                                startDate.config.max = {
                                    year: date.year,
                                    month: date.month - 1,
                                    date: date.date,
                                    hours: date.hours,
                                    minutes: 0,
                                    seconds: 0
                                } 
                            }else {
                                startDate.config.min = commonMin;
                                startDate.config.max = commonMax; 
                            }
                        }
                    });
                    break;
                    default:
                    break;
                }
                
            })
        }

        //表格渲染事件
        function renderTable(data) {
            data.delTr = function(id) {
                var newUsers = [];
                $.each(tableUsers, function(index,item) {
                    if(item.writeuserid !== id) {
                        newUsers.push(item)
                    }
                });
                tableUsers = newUsers;
                renderTable({users: tableUsers, dates: tableDates})
            };
            view('attence-table-page').render('./task/permanent/table',data);
        };

        //搜索区域时间绑定
        function bindSearchTime() {
            var $timeContainer = $('.attence-search-form');
            var commonMin = { year: 1900, month: 0, date: 1},
                commonMax = { year: 2099, month: 11, date: 31};
            var startDate = laydate.render({
                elem: $timeContainer.find('.item-time-start').get(0),
                done: function (value, date) {
                    if(!!value) {
                        endDate.config.min = {
                            year:date.year-1,
                            month:date.month-1, 
                            date: date.date,
                        };
                        endDate.config.max ={
                            year: date.year+1,
                            month:date.month-1, 
                            date: date.date,
                        };
                    }else {
                        endDate.config.min = commonMin;
                        endDate.config.max = commonMax;
                    }
                    var endTime = $timeContainer.find('.item-time-end').val();
                    if(value && endTime) {
                        if(moment(value).isAfter(endTime)) {
                            $timeContainer.find('.item-time-end').val('');
                        }else {
                            searchKQTime({
                                starttime: value,
                                endtime: endTime
                            });
                        }
                    }
                }
            })
            var endDate = laydate.render({
                elem: $timeContainer.find('.item-time-end').get(0),
                done: function (value, date) {
                    if(!!value) {
                        startDate.config.min = {
                            year: date.year-1,
                            month: date.month - 1,
                            date: date.date,
                        } 
                        startDate.config.max = {
                            year: date.year,
                            month: date.month - 1,
                            date: date.date,
                        } 
                    }else {
                        startDate.config.min = commonMin;
                        startDate.config.max = commonMax; 
                    }
                    var starttime = $timeContainer.find('.item-time-start').val();

                    if(starttime && value) {
                        if(moment(starttime).isAfter(value)) {
                            $timeContainer.find('.item-time-start').val('');
                        }else {
                            searchKQTime({
                                starttime: starttime,
                                endtime: value
                            });
                        }
                    }
                }
            });
        }

        //新增
        function addInit() {
            admin.req({
                url: 'myapi/DC/api/rest/web/custom/CheckTaskDataSelect',
                type: 'get',
                data: {model:'addSelect'},
                success: function(res){
                    var initData = res.data.data;
                    var dates = initData.users[0].users_time[0].users_time_day;
                    form.render(null, 'attence-search-form');
                    initData.dates = dates;
                    tableUsers = initData.users;
                    tableDates = dates;
                    renderTable(initData);
                }
            });
        }

        //考勤时间搜索，并渲染表格
        function searchKQTime(args) {
            admin.req({
                url: 'myapi/DC/api/rest/web/custom/CheckTaskDateSelect',
                type: 'get',
                data: args,
                success: function(res){
                    tableDates = res.data.data.users_time_day;
                    renderTable({users: tableUsers, dates: tableDates});
                }
            });
        }

        var selectDep = d.params.deptMsg || [],
            selectGrp = d.params.groupMsg || [],
            originDep = [],
            originGrp = [];
            $.each(selectDep, function(i,e) {
                e.dept_id = e.dataid;
                originDep.push(e);
            });
            $.each(selectGrp, function(i,e) {
                e.dept_id = e.dataid;
                originGrp.push(e);
            });

        //时间频率相关操作
        $('.attence-updateHtml-content').on('click', '.T-bEvent', function() {
            var target = $(this).data('target');
            switch(target) {
                case 'addItem':
                    var itemLength = $(this).closest('.dateType').find('.date-item').length;
                    if(itemLength === 5) {
                        return false;
                    }
                    insertDateTplByType(false);
                break;
                case 'delItem':
                    var $item = $(this).closest('.date-item');
                    $item.remove();
                break;
                default:
                break;
            }
        })

        //页面按钮点击事件
        $('.attence-updateHtml-content').on('click', '.T-event', function() {
            var $container = $('.attence-updateHtml-content');
            var target = $(this).data('target');
            if($(this).hasClass("unit")){
                var text = "单位";
            }else{
                var text = "群组";
            }
            if(target === 'add') { 
                function getResultArr(originArr, selectArr) {
                    var resultArr = [];
                    $.each(originArr,function(index, item) {
                        var isShowOut = false;
                        $.each(selectArr, function(i, e) {
                            if(item.dept_id === e.dept_id) {
                                item.model = 'normal';
                                resultArr.push(item);
                                isShowOut = true;
                            }
                        });
                        if(!isShowOut) {
                            item.model = 'del';
                            resultArr.push(item);
                        }
                    });
                    $.each(selectArr,function(index, item) {
                        var isShowInner = false;
                        $.each(originArr, function(i, e) {
                            if(item.dept_id === e.dept_id) {
                                isShowInner = true;
                            }
                        });
                        if(!isShowInner) {
                            item.model = 'insert';
                            item.taskid = d.params.id || '';
                            item.dataid = item.dept_id;
                            resultArr.push(item);
                        }
                    });
                    return resultArr;
                }
                if(tableUsers.length > 100) {
                    layer.msg('考勤人员不可超过100');
                    return false;
                }
                var resultDep = getResultArr(originDep, selectDep),
                    resultGrp = getResultArr(originGrp, selectGrp);
                var $form = $('.attence-updateHtml-content .attence-frequency-form');
                var arr = tools.getAreaArgs($form.find('.dateType .date-item'), {type: 'array'});
                var args = tools.getAreaArgs($('.attence-updateHtml-form'), {input: 1});
                if(!args.taskname) {
                    layer.msg('请先填写任务名称');
                    return false;
                }
                var hz = $('.frequencyType').find('input[name="frequencyType"]:checked').val();
                var settype = $form.find('input[name="timeType"]:checked').val() === 'frequency' ? 0 : 1;
                var timeDate = [];
                $.each(arr, function(index, item) {
                    if(!!item.starttime && !!item.endtime) {
                        item.starttime = moment(item.starttime).format('YYYY-MM-DD HH:mm:ss');
                        item.endtime = moment(item.endtime).format('YYYY-MM-DD HH:mm:ss');
                        item.hz = hz;
                        item.settype = settype;
                        timeDate.push(item);
                    }
                });
                if(timeDate.length === 0) {
                    layer.msg('请先选择至少一组开始结束时间');
                    return false;
                }
                args.fileNames = JSON.stringify(filenames);
                args.timeDate = JSON.stringify(timeDate);
                args.model = 'insert';
                args.updatedata = '0';
                args.users = JSON.stringify(tableUsers);
                args.dates = JSON.stringify(tableDates);
                args.jsonId = layui.data('layuiAdmin').access_token;
                if(!!d.params.id) {
                    args.model = 'update';
                    args.updatedata = '1';
                }
                admin.req({
                    url: 'myapi/DC/api/rest/web/custom/CheckTaskDataSave',
                    type: 'post',
                    data: args,
                    success: function(res) {   
                        if(res.data.retcode == '0'){  
                            if(res.data.updateChild=="0"){
                                layer.confirm('是否重新生成子任务？（提示：当前正在填报的子任务将被删除，再重新创建）', {icon: 3, title:'提示'}, function(index){
                                    admin.req({ 
                                        url: 'myapi/DC/api/rest/web/custom/CheckTaskDataUpdateSubtask',
                                        type: 'get',
                                        data: {
                                            taskid:d.params.taskid,
                                            access_token: layui.data('layuiAdmin').access_token,
                                        },
                                        success: function(res){  
                                            layer.msg(res.data.retmsg,{time:1000},function(){ 
                                                d.params.callBack && d.params.callBack();
                                            }); 
                                        }
                                    });
                                    layer.close(index); 
                                    window.reload();
                                });
                            }else{
                                layer.msg(res.data.retmsg);
                            }  
                            layer.closeAll('page');
                        }else{
                            layer.msg(res.data.retmsg);
                        } 
                        d.params.callBack && d.params.callBack();
                    }
                });
            } else if (target === 'unit') {
                if(text=="单位"){
                    var attenceUrl = "./task/temporary/past"
                }else{
                    var attenceUrl = "./task/temporary/pastGroup"
                }
                layer.open({
                    id: 'attence-add-pastHtml',
                    title:'<i class="formFill-icon"></i><span style="color:#FFF;">任务下发</span>',
                    offset: '20px',
                    type: 1,
                    shadeClose: true,
                    area: ['450px', '650px'],
                    success: function(lay, index) {
                        view(this.id).render(attenceUrl, {
                            exitDep: selectDep,
                            exGgrp: selectGrp
                        }).done(function() {
                            $(lay).on('click', '.T-confirm', function() {
                                if(text=="单位"){
                                    selectDep = JSON.parse($(lay).find('.data-dep-container').val());
                                    var depNameStr = selectDep;
                                    var getTpl = attenceselectunitTpl.innerHTML;
                                    var $tplC =$('.attence-update-department').eq(0);
                                }else{
                                    selectGrp = JSON.parse($(lay).find('.data-group-container').val());
                                    var depNameStr = selectGrp;
                                    var getTpl = attenceselectgroupTpl.innerHTML;
                                    var $tplC =$('.attence-update-department').eq(1);
                                }
                                laytpl(getTpl).render(depNameStr, function(html){
                                    $tplC.html(html);
                                });
                                layer.close(index);
                            });
                        });
                    }
                });
            } else if (target === 'delUnit') {
                var depid = $(this).data('deptid');
                if($(this).hasClass("unit")){
                    var textClose = "单位";
                }else{
                    var textClose = "群组";
                }
                if(textClose=="单位"){
                    var filterDep = [];
                    $.each(selectDep, function(index) {
                        if(selectDep[index].dept_id !== depid) {
                            filterDep.push(selectDep[index]);
                        }
                    });
                    selectDep = filterDep;
                    var depNameStr = filterDep;
                    var getTpl = attenceselectunitTpl.innerHTML;
                    var $tplC =$('.attence-update-department').eq(0);
                }else{
                    var filterGrp = [];
                    $.each(selectGrp, function(index) {
                        if(selectGrp[index].dept_id !== depid) {
                            filterGrp.push(selectGrp[index]);
                        }
                    });
                    selectGrp = filterGrp;
                    var depNameStr = filterGrp;
                    var getTpl = attenceselectgroupTpl.innerHTML;
                    var $tplC =$('.attence-update-department').eq(1);
                }        
                laytpl(getTpl).render(depNameStr, function(html){
                    $tplC.html(html);
                });
            } else if (target === 'delFile') {
                var depid = $(this).data('deptid');
                admin.req({
                    url: 'myapi/DC/api/rest/web/custom/Resident/delfile',
                    type: 'post',
                    data: {servername: depid},
                    success: function(res){
                        if(res.retcode == 0) {
                            var filterFiles = [];
                            $.each(filenames, function(index) {
                                if(filenames[index].servername !== depid) {
                                    filterFiles.push(filenames[index]);
                                }
                            });
                            filenames = filterFiles;
                            var getTpl = attenceuploadFilesTpl.innerHTML;
                            var $tplC =$('.attence-update-files');
                            laytpl(getTpl).render(filenames, function(html){
                                $tplC.html(html);
                            });
                        }
                    }
                });
            } else if (target === 'viewlast') {
                var $form = $('.attence-updateHtml-content .attence-frequency-form');
                var arr = tools.getAreaArgs($form.find('.dateType .date-item'), {type: 'array'}, function($obj) {
                    var starttime = $obj.find('.item-time-start').val(),
                        endtime = $obj.find('.item-time-end').val();
                    return !!starttime && !!endtime;
                });
                // var hz = $form.find('input[name="frequencyType"]').val();
                var hz = $('.frequencyType').find('input[name="frequencyType"]:checked').val();
                var timeDate = [];
                $.each(arr, function(index, item) {
                    item.starttime = moment(item.starttime).format('YYYY-MM-DD HH:mm:ss');
                    item.endtime = moment(item.endtime).format('YYYY-MM-DD HH:mm:ss');
                    timeDate.push(item);
                })
                var args = {
                    hz: hz,
                    timeDate: timeDate
                }
                if(timeDate.length === 0) {
                    layer.msg('请先选择至少一组开始结束时间');
                    return false;
                }
                admin.req({
                    url: 'myapi/DC/api/rest/web/custom/getthelatesttime',
                    type: 'post',
                    data: {time: JSON.stringify(args)},
                    success: function(res){
                        var getTpl = attenceShowLastTpl.innerHTML;
                        var $tplC =$('.attence-frequency-form .listType .body');
                        laytpl(getTpl).render(res.data, function(html){
                            $tplC.html(html);
                        });
                    }
                });
            }else if (target === 'download') {
                var url = 'myapi/DC'+ $(this).data('url'),
                    name = $(this).text();
                tools.downMethodfunction(url, name);
            }else if(target == 'to-review'){
					var text = $(this).text();
					var reviewUrl = null;
					if(text == '附加复核人：'){
						reviewUrl = './task/temporary/addPerson'
					}else{
						reviewUrl = './task/temporary/pullPerson'
					}
					layer.open({
						id: 'temporary-reviewHtml',
						title: text,
						type: 1,
						offset: '20px',
						shadeClose: true,
						area: ['600px', '650px'],
						success: function(lay, index){
							view(this.id).render(reviewUrl, {
								// exitDep: selectDep,
								// exGgrp: selectGrp
							}).done(function() {
								$(lay).on('click', '.T-confirm', function() {
									if(text == "附加复核人："){
                                        var selectReview = JSON.parse((lay).find('.data-review-container').val());
										$('.review-value-box').html(JSON.stringify(selectReview.join(',')).replace(/"/g, ''));
									}else{
										var selectAudit = JSON.parse($(lay).find('.data-audit-container').val());
										$('.audit-value-box').html(JSON.stringify(selectAudit.join(',')).replace(/"/g, ''));
									}
									layer.close(index);
								});
							});
						}
					})
			}
        });

        //搜索区域按钮点击事件
        $('.table-area').on('click','.layui-btn', function() {
            var target= $(this).data('target'),
                $dateC = $(this).closest('.date-group');
            switch(target) {
                case 'search':
                    var args = tools.getAreaArgs($dateC);
                    if(!args.starttime || !args.endtime) {
                        layer.msg('请选择考勤时间');
                        return false;
                    }
                    searchKQTime(args);
                break;
                case 'choice':
                layer.open({
                    id: 'managerSet-delUnit-pastHtml',
                    title: '<i class="formFill-icon"></i><span style="color:#FFF;">选择人员</span>',
                    offset: '80px',
                    type: 1,
                    shadeClose: true,
                    area: ['600px', '650px'],
                    success: function(lay, index){
                        view(this.id).render('./task/temporary/addPerson', {
                            onlyUnit: '1'
                        }).done(function() {
                            $(lay).on('click', '.T-confirm', function() {
                                var selectReview = $(lay).find('.check-value-box .unit-content'),
                                    jsonArr = [];
								$.each(selectReview, function(index, item){
									var certcode = item.querySelector('.del-tag').getAttribute('data-certcode'),
                                        username = item.querySelector('a').innerText;
                                    jsonArr.push({writeuserid: certcode, writeusername: username});
                                })
                                tableUsers = tools.uniqueArr(jsonArr.concat(tableUsers), 'writeuserid');
                                renderTable({users: tableUsers, dates: tableDates});
                                layer.close(index);
                            });
                        });
                    }
                });
                break;
                default:
                break;
            }
        });
    });
}

</script>